import { Application, FrontendSession } from 'pinus';
import * as Crypto from 'crypto';

 
import WechatUtil from '../../../utils/wechat_util'
import NetResult from '../../../consts/net_result';
import orm_util from '../../../utils/orm_util';
import { User } from '../../../entity/user.entity';
import { LoginType } from '../../../consts/login_type';
import { UserService } from '../../../services/user_service';

export default function (app: Application) {
    return new Handler(app);
}

 

 

export class Handler {
    constructor(private app: Application) {
        
    }

    /**
     * New client entry.
     *
     * @param  {Object}   msg     request message
     * @param  {Object}   session current session object
     * @param  {Function} next    next step callback
     * @return {Void}
     */
    async entry(msg: any, session: FrontendSession) {
        console.log("entry..call..",msg)
        switch(msg.loginType){
            case LoginType.WechatMini:
                return await UserService.ins().loginByWechatMini(msg.code);
            case LoginType.Test:
                return await UserService.ins().loginByTest(this.app,session);
                default:
                return NetResult.error(null,"不支持的登录方式");
        }
    }
 

   

    async loginByWechatMini2(msg: any, session: FrontendSession) {
        // console.dir(msg)
        // let sessionKey = Buffer.from(msg.session_key, 'base64')
        // msg.encryptedData = Buffer.from(msg.encryptedData, 'base64')
        // msg.iv = Buffer.from(msg.iv, 'base64');
        // try {
        //     let decipher = Crypto.createDecipheriv('aes-128-cbc', sessionKey, msg.iv);
        //     decipher.setAutoPadding(true);
        //     let decoded:any = decipher.update(msg.encryptedData, 'binary', 'utf8');
        //     decoded += decipher.final('utf8');
        //     decoded = JSON.parse(decoded);
        //   if (decoded.watermark.appid !== WechatUtil.appId) {
        //     return NetResult.error("Appid不合法");
        //   }
        //   console.dir(decoded);
        //   let userRepository=await orm_util.getRepository(User);
        //   let user=await userRepository.findOne({ uniqueKey: decoded.openId });
        //   if(!user){
        //      user=new User();
        //   }
        //   user.nickName=decoded.nickName;
        //   user.uniqueKey=decoded.openId;
        //   user.man=!!decoded.gender;
        //   user.country=decoded.country;
        //   user.avatarUrl=decoded.avatarUrl;
        //   user.loginType=LoginType.WechatMini;
        //   userRepository.save(user);

        //   await UserService.setSessionUser(this.app,session,user);
        //   return NetResult.success();
        // } catch (err) {
        //     console.dir(err);
        //     return NetResult.error();
        //   }
        
    }

   

}